package com.yzd.learnjava.concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.yzd.learnjava.util.Print;

public class SerialNumberChecker {
	private static final int SIZE = 10;
	private static CircularSet serials = new CircularSet(1000);
	private static ExecutorService exec = Executors.newCachedThreadPool();
	
	static class SerialChecker implements Runnable{
		public void run() {
			while(true) {
				int serial = SerialNumberGenerator.nextSerialNumber();
				if(serials.contains(serial)) {
					Print.print("Duplicate: " + serial);
					System.exit(0);
				}
				serials.add(serial);
			}
		}
	}
	
	public static void main(String[] args) {
		for(int i = 0; i < SIZE; i++) {
			exec.execute(new SerialChecker());
		}
	}
}

class CircularSet{
	private int[] array;
	private int length;
	private int index = 0;
	public CircularSet(int size) {
		array = new int[size];
		length = size;
		for(int i = 0 ; i < size ; i++) {
			array[i] = -1;
		}
	}
	
	public synchronized void add(int n) {
		array[index] = n;
		
		index = ++index % length; 
	}
	
	public synchronized boolean contains(int value) {
		for(int i = 0 ; i < length; i++) {
			if(array[i] == value) {
				return true;
			}
		}
		return false;
	}
	
	
}
